package com.hcb.tonguetiphealth.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.ChatActivity;
import com.hcb.tonguetiphealth.view.R;

public class TongueTipHealthServiceLiuYan extends Service {
	public static final int ID_NOTIFICATION = 1;
	private static final String TAG = "TongueTipHealthServiceLiuyan";
	private String url_receiveLiuyan = Global.URL + Global.servlet_receiveLiuyan;
	
	private static boolean processing = true;
	private Handler handler;
	private static Handler chatHandler;
	private String response;
	public static void setChatHandler(Handler chatHandler) {
		TongueTipHealthServiceLiuYan.chatHandler = chatHandler;
	}
	private void sendChatNotification(){
		if(chatHandler != null) {
			Message msg = chatHandler.obtainMessage(MessageWhat.CHAT_NOTIFICATION_LIUYAN, response);
			System.out.println("servrice reesponse:"+response);
			msg.sendToTarget();
		}
	}
	private User user;
	

	@Override
	public IBinder onBind(Intent arg0) {
		System.out.println("TongueTipHealthServiceLiuyan -------------------- onBind");
		return null;
	}

	@Override
	public void onCreate() {
		System.out.println("TongueTipHealthServiceLiuyan -------------------- onCreate");
		/*handler = new Handler() {
			
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.CHAT_LIUYAN_RECEIVED:
					addNotificaction();
					processing = false;
					break;
				}
			}
			
		};*/
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		System.out.println("TongueTipHealthServiceliuyan -------------------- onDestroy");
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		System.out.println("TongueTipHealthServiceLiuyan -------------------- onStart");
		new Thread() {
			public void run() {
				while (true) {
					if (Global.user != null && !isAppRunning()) {
						System.out.println("user:-------"+Global.user.getUserName());
						checkChat();
					}
					for (int i = 0; i < 20; i++) {
						try {
							Thread.sleep(500);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
					}
					
				}
				
			}
		}.start();
	}
	/**
	 * 查看是否有留言
	 */
	private void checkChat() {
		try {
			List <NameValuePair> params = new ArrayList <NameValuePair>();
			params.add(new BasicNameValuePair("userName", Global.user.getUserName()));
			response = HttpUtils.Post1(url_receiveLiuyan, params);
			
			if(Global.DEBUG) {
				System.out.println("receiveLiuyan -----------------------------\n" + response);
			}
		} catch(Exception e) {
			Log.e(TAG, "Exception", e); 
		}
		if(!StringUtils.isEmpty(response)) {
			JSONManager jManager = new JSONManager();
			boolean isGotJSONObject = jManager.isGotJSONObject(response);
			if(isGotJSONObject) {
				addNotificaction();
			}
		}
	}
	
	/** 
     * 添加一个notification 
     */  
    private void addNotificaction() {  
        NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);  
        // 创建一个Notification  
        Notification notification = new Notification();  
        // 设置显示在手机最上边的状态栏的图标  
        notification.icon = R.drawable.ic_launcher;  
        // 当当前的notification被放到状态栏上的时候，提示内容  
        notification.tickerText = "您收到了新消息";  
          
        /*** 
         * notification.contentIntent:一个PendingIntent对象，当用户点击了状态栏上的图标时，该Intent会被触发 
         * notification.contentView:我们可以不在状态栏放图标而是放一个view 
         * notification.deleteIntent 当当前notification被移除时执行的intent 
         * notification.vibrate 当手机震动时，震动周期设置 
         */  
        // 添加声音提示  
        notification.defaults = Notification.DEFAULT_SOUND;  
        // audioStreamType的值必须AudioManager中的值，代表着响铃的模式  
        notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;  
        notification.when = System.currentTimeMillis();
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        
        //下边的两个方式可以添加音乐  
        //notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");   
        //notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");   
        
        Intent intent = new Intent(this, ChatActivity.class);  
        intent.putExtra("from", "TongueTipHealthServiceLiuYan");
        intent.putExtra("response", response);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); 
        
        // 点击状态栏的图标出现的提示信息设置  
        notification.setLatestEventInfo(this, "新消息", "您有新消息！", pendingIntent);  
        manager.notify(ID_NOTIFICATION, notification);  
        
        sendChatNotification();
        //manager.cancel(ID_NOTIFICATION);
    }

	public static boolean isProcessing() {
		return processing;
	}

	public static void setProcessing(boolean process) {
		processing = process;
	}
	
	//判断应用程序是否在前台运行
	 protected boolean isAppRunning() {
		 String packageName = "com.hcb.tonguetiphealth.view";
			ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
		    List<RunningTaskInfo>  tasksInfo = am.getRunningTasks(1);  
		    if(tasksInfo.size() > 0){  
	            System.out.println("---------------包名-----------"+tasksInfo.get(0).topActivity.getPackageName());
	            //应用程序位于堆栈的顶层  
	            if(packageName.equals(tasksInfo.get(0).topActivity.getPackageName())){  
	                return true;  
	            }  
	        }  
	        return false;
	}
}
